<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Tymon\JWTAuth\Facades\JWTAuth;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    private $_user = null;

    //需要返回的数据
    protected $result = [];

    /**
     * 返回处理成功数据
     */
    protected function success($data = [], $msg = '操作成功')
    {
        $this->result = ['code' => 200, 'message' => $msg, 'msg' => $msg, 'data' => $data];
        return $this->destroy();
    }

    /**
     * 返回失败信息
     */
    protected function error($msg = 'error', $data = [], $code = 10000, $statusCode = 200)
    {
        $this->result = ['code' => $code, 'message' => $msg, 'msg' => $msg, 'data' => $data];
        return $this->destroy($statusCode);
    }

    /**
     * 响应数据
     */
    private function destroy($statusCode = 200)
    {
        return response()->json($this->result, $statusCode);
    }

    /**
     * 获取当前用户
     * @return \App\Models\User
     * @author lijiefneg
     * @date   2021/3/15 17:38
     */
    protected function getAuthenticatedUser()
    {
        try {
            if (!empty($this->_user)) { //避免多次调用该函数查询数据库
                return $this->_user;
            };
            $user = JWTAuth::parseToken()->authenticate();
            $this->_user = $user;
            return $this->_user;
        } catch (\Exception $exception) {
            return false;
        }
    }
}
